import 'package:flutter/material.dart';
import '../utils/word_import_export_util.dart';
import '../utils/word_export_util.dart';
import '../models/question.dart';
import '../services/database_service.dart';
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import 'package:csv/csv.dart';

class QuestionImportExportScreen extends StatefulWidget {
  final List<Map<String, dynamic>>? initialQuestions;
  
  const QuestionImportExportScreen({Key? key, this.initialQuestions}) : super(key: key);

  @override
  _QuestionImportExportScreenState createState() => _QuestionImportExportScreenState();
}

class _QuestionImportExportScreenState extends State<QuestionImportExportScreen> {
  List<Map<String, dynamic>> _questions = [];
  String _statusMessage = '';
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    
    // 如果有初始题目数据，则加载它
    if (widget.initialQuestions != null && widget.initialQuestions!.isNotEmpty) {
      _questions = widget.initialQuestions!;
      _statusMessage = '已加载${_questions.length}个题目';
    } else {
      _statusMessage = '请选择操作';
    }
  }

  // 创建示例题目数据
  Future<void> _createSampleQuestions() async {
    final sampleQuestions = [
      {
        'type': 'logical_reasoning',
        'category': '逻辑推理',
        'point': '演绎推理',
        'content': '如果所有的猫都有尾巴，而汤姆是一只猫，那么可以推断出',
        'question_image_url': '',
        'option_a': '汤姆有尾巴',
        'option_a_image_url': '',
        'option_b': '汤姆没有尾巴',
        'option_b_image_url': '',
        'option_c': '不能确定汤姆是否有尾巴',
        'option_c_image_url': '',
        'option_d': '以上都不对',
        'option_d_image_url': '',
        'correct_answer': 'A',
        'explanation': '这是一个简单的三段论推理',
        'explanation_image_url': ''
      },
      {
        'type': 'quantitative_relation',
        'category': '数量关系',
        'point': '数列规律',
        'content': '找出下列数列的规律并填入问号处：2, 5, 11, 23, 47, ?',
        'question_image_url': '',
        'option_a': '23',
        'option_a_image_url': '',
        'option_b': '95',
        'option_b_image_url': '',
        'option_c': '191',
        'option_c_image_url': '',
        'option_d': '383',
        'option_d_image_url': '',
        'correct_answer': 'B',
        'explanation': '数列规律是：每项是前一项的2倍加1',
        'explanation_image_url': ''
      },
      {
        'type': 'politics',
        'category': '政治',
        'point': '马克思主义',
        'content': '马克思主义哲学的基本问题是',
        'question_image_url': '',
        'option_a': '物质和意识的关系问题',
        'option_a_image_url': '',
        'option_b': '实践和认识的关系问题',
        'option_b_image_url': '',
        'option_c': '社会存在和社会意识的关系问题',
        'option_c_image_url': '',
        'option_d': '真理和谬误的关系问题',
        'option_d_image_url': '',
        'correct_answer': 'A',
        'explanation': '马克思主义哲学的基本问题是物质和意识的关系问题',
        'explanation_image_url': ''
      },
      {
        'type': 'common_sense',
        'category': '常识',
        'point': '科学常识',
        'content': '下列哪项不是太阳系的行星',
        'question_image_url': '',
        'option_a': '水星',
        'option_a_image_url': '',
        'option_b': '金星',
        'option_b_image_url': '',
        'option_c': '冥王星',
        'option_c_image_url': '',
        'option_d': '土星',
        'option_d_image_url': '',
        'correct_answer': 'C',
        'explanation': '冥王星在2006年被国际天文学联合会重新归类为矮行星',
        'explanation_image_url': ''
      },
      {
        'type': 'verbal_comprehension',
        'category': '言语理解',
        'point': '词语辨析',
        'content': '下列词语中，与"博学"意思最接近的是',
        'question_image_url': '',
        'option_a': '博大',
        'option_a_image_url': '',
        'option_b': '博爱',
        'option_b_image_url': '',
        'option_c': '博览',
        'option_c_image_url': '',
        'option_d': '博古通今',
        'option_d_image_url': '',
        'correct_answer': 'D',
        'explanation': '博古通今意为对古代和现代的知识都精通，与博学最为接近',
        'explanation_image_url': ''
      },
      {
        'type': 'data_analysis',
        'category': '资料分析',
        'point': '数据解读',
        'content': '某市2020年GDP为1000亿元，2021年增长10%，2022年增长8%，则2022年该市GDP为多少亿元？',
        'question_image_url': '',
        'option_a': '1180亿元',
        'option_a_image_url': '',
        'option_b': '1188亿元',
        'option_b_image_url': '',
        'option_c': '1080亿元',
        'option_c_image_url': '',
        'option_d': '1800亿元',
        'option_d_image_url': '',
        'correct_answer': 'B',
        'explanation': '2021年GDP为1000×(1+10%)=1100亿元，2022年GDP为1100×(1+8%)=1188亿元',
        'explanation_image_url': ''
      }
    ];
    
    setState(() {
      _questions = sampleQuestions;
      _statusMessage = '已创建${_questions.length}个示例题目';
    });
    
    // 询问用户是否要保存到数据库
    final shouldSave = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('保存到数据库', style: TextStyle(fontFamily: 'FangSong')),
          content: const Text('是否将示例题目保存到数据库？', style: TextStyle(fontFamily: 'FangSong')),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
            ),
          ],
        ),
      ) ?? false;
    
    if (shouldSave) {
      await _saveQuestionsToDatabase(sampleQuestions);
    }
  }

  // 显示导出选项对话框
  Future<void> _exportQuestions() async {
    if (_questions.isEmpty) {
      setState(() {
        _statusMessage = '没有题目可导出，请先创建示例题目';
      });
      return;
    }
    
    // 显示导出格式选择对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择导出格式', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.table_chart),
              title: const Text('CSV格式', style: TextStyle(fontFamily: 'FangSong')),
              onTap: () {
                Navigator.pop(context);
                _exportToCSV();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.description),
              title: const Text('Word格式 - 仅题目', style: TextStyle(fontFamily: 'FangSong')),
              onTap: () {
                Navigator.pop(context);
                _exportToWord(WordExportType.questionsOnly);
              },
            ),
            ListTile(
              leading: const Icon(Icons.question_answer),
              title: const Text('Word格式 - 题目+答案+解析', style: TextStyle(fontFamily: 'FangSong')),
              onTap: () {
                Navigator.pop(context);
                _exportToWord(WordExportType.questionsWithAnswers);
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
          ),
        ],
      ),
    );
  }
  
  // 导出题目到CSV
  Future<void> _exportToCSV() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导出题目到CSV...';
    });

    try {
      final filePath = await WordImportExportUtil.exportQuestionsToCSV(_questions);
      setState(() {
        _isLoading = false;
        _statusMessage = '题目导出成功: $filePath';
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '题目导出失败: $e';
      });
    }
  }
  
  // 导出题目到Word
  Future<void> _exportToWord(WordExportType exportType) async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导出题目到Word...';
    });

    try {
      // 将Map格式的题目转换为Question对象
      final now = DateTime.now().millisecondsSinceEpoch;
      final List<Question> questionObjects = _questions.map((q) => Question(
        id: null,
        type: q['type'] ?? 'common_sense',
        question: q['content'] ?? '',
        optionA: q['option_a'] ?? '',
        optionB: q['option_b'] ?? '',
        optionC: q['option_c'] ?? '',
        optionD: q['option_d'] ?? '',
        correctAnswer: q['correct_answer'] ?? '',
        explanation: q['explanation'] ?? '',
        questionImageUrl: q['question_image_url'] ?? '',
        optionAImageUrl: q['option_a_image_url'] ?? '',
        optionBImageUrl: q['option_b_image_url'] ?? '',
        optionCImageUrl: q['option_c_image_url'] ?? '',
        optionDImageUrl: q['option_d_image_url'] ?? '',
        keyPoint: q['point'] ?? '',
        category: q['category'] ?? '',
        created_at: now,
        updated_at: now,
      )).toList();
      
      // 导出到Word
      final filePath = await WordExportUtil.exportQuestionsToWord(
        questionObjects,
        exportType: exportType,
      );
      
      setState(() {
        _isLoading = false;
        _statusMessage = '题目导出成功: $filePath';
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '题目导出失败: $e';
      });
    }
  }

  // 将题目保存到数据库的通用方法
  Future<void> _saveQuestionsToDatabase(List<Map<String, dynamic>> questionsData) async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在保存题目到数据库...';
    });
    try {
      // 初始化数据库服务
      final databaseService = DatabaseService();
      await databaseService.init();
      
      // 将题目数据转换为Question对象
      final List<Question> questions = [];
      final now = DateTime.now().millisecondsSinceEpoch;
      
      for (var q in questionsData) {
        final question = Question(
          question: q['content'],
          questionImageUrl: q['questionImageUrl'] ?? q['question_image_url'],
          optionA: q['optionA'] ?? q['option_a'],
          optionAImageUrl: q['optionAImageUrl'] ?? q['option_a_image_url'],
          optionB: q['optionB'] ?? q['option_b'],
          optionBImageUrl: q['optionBImageUrl'] ?? q['option_b_image_url'],
          optionC: q['optionC'] ?? q['option_c'],
          optionCImageUrl: q['optionCImageUrl'] ?? q['option_c_image_url'],
          optionD: q['optionD'] ?? q['option_d'],
          optionDImageUrl: q['optionDImageUrl'] ?? q['option_d_image_url'],
          correctAnswer: q['correctAnswer'] ?? q['correct_answer'],
          explanation: q['explanation'],
          explanationImageUrl: q['explanationImageUrl'] ?? q['explanation_image_url'],
          category: q['category'],
          keyPoint: q['keyPoint'] ?? q['point'],
          type: q['type'],
          created_at: now,
          updated_at: now,
        );
        questions.add(question);
      }
      
      // 批量保存题目到数据库
      final savedIds = await databaseService.questionRepository.addQuestions(questions);
      setState(() {
        _isLoading = false;
        _statusMessage = '成功保存${questions.length}个题目到数据库';
      });
      
      return;
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '保存题目到数据库失败: $e';
      });
      rethrow;
    }
  }
  
  // 导入题目
  Future<void> _importQuestions() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在导入题目...';
    });
    try {
      final importedQuestions = await WordImportExportUtil.importQuestionsFromCSVOrExcel();
      
      setState(() {
        _isLoading = false;
        _questions = importedQuestions;
        _statusMessage = '成功导入${importedQuestions.length}个题目';
      });
      
      // 询问用户是否要保存到数据库
      final shouldSave = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('保存到数据库', style: TextStyle(fontFamily: 'FangSong')),
          content: const Text('是否将导入的题目保存到数据库？', style: TextStyle(fontFamily: 'FangSong')),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
            ),
          ],
        ),
      ) ?? false;
      
      if (shouldSave) {
        await _saveQuestionsToDatabase(importedQuestions);
      } else {
        setState(() {
          _isLoading = false;
          _statusMessage = '已取消保存导入的题目';
        });
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '题目导入失败: $e';
      });
    }
  }
  
  // 批量导入题目
  Future<void> _importMultipleQuestions() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在批量导入题目...';
    });
    try {
      // 选择多个CSV文件
      final typeGroup = XTypeGroup(
        label: 'CSV',
        extensions: ['csv'],
      );
      final List<XFile> files = await openFiles(
        acceptedTypeGroups: [typeGroup],
      );

      if (files.isEmpty) {
        setState(() {
          _isLoading = false;
          _statusMessage = '未选择文件';
        });
        return;
      }
      
      int totalImported = 0;
      List<Map<String, dynamic>> allImportedQuestions = [];
      
      // 处理每个文件
      for (var file in files) {
        // 读取文件内容
        final fileContent = await file.readAsString();
        
        // 解析CSV
        List<List<dynamic>> csvTable = const CsvToListConverter().convert(fileContent);
        
        if (csvTable.isEmpty) {
          continue;
        }
        
        // 获取标题行，用于识别列
        List<dynamic> headers = csvTable.isNotEmpty ? csvTable[0] : [];
        // 使用工具类识别列映射
        Map<String, int> columnMap = WordImportExportUtil.identifyQuestionColumns(headers);
        
        // 跳过标题行，解析数据行
        List<Map<String, dynamic>> fileQuestions = [];
        for (int i = 1; i < csvTable.length; i++) {
          final row = csvTable[i];
          // 使用列映射获取题目内容
          String content = '';
          if (columnMap.containsKey('content') && columnMap['content']! < row.length) {
            content = row[columnMap['content']!].toString().trim();
          } else if (row.length >= 4) {
            content = row[3].toString().trim();
          }
          
          if (content.isNotEmpty) { // 至少要有题目内容
            // 获取类型并确保它是有效的类型
            String type = row.length > 0 ? row[0].toString().trim() : '';
            // 验证类型是否为有效的预定义类型
             if (!WordImportExportUtil.isValidQuestionType(type)) {
               print('警告: ${file.name} 第${i+1}行的题目类型"$type"无效，将使用默认类型"common_sense"');
               type = 'common_sense';
             }
            
            // 创建题目数据，保留原始图片路径（不使用validateImagePath以避免本地路径丢失）
            fileQuestions.add({
              'type': type,
              'category': row.length > 1 ? row[1].toString().trim() : '',
              'point': row.length > 2 ? row[2].toString().trim() : '',
              'content': row.length > 3 ? row[3].toString().trim() : '',
              'questionImageUrl': row.length > 4 ? row[4].toString().trim() : '',
              'optionA': row.length > 5 ? row[5].toString().trim() : '',
              'optionAImageUrl': row.length > 6 ? row[6].toString().trim() : '',
              'optionB': row.length > 7 ? row[7].toString().trim() : '',
              'optionBImageUrl': row.length > 8 ? row[8].toString().trim() : '',
              'optionC': row.length > 9 ? row[9].toString().trim() : '',
              'optionCImageUrl': row.length > 10 ? row[10].toString().trim() : '',
              'optionD': row.length > 11 ? row[11].toString().trim() : '',
              'optionDImageUrl': row.length > 12 ? row[12].toString().trim() : '',
              'answer': row.length > 13 ? row[13].toString().trim() : '',
              'explanation': row.length > 14 ? row[14].toString().trim() : '',
              'explanationImageUrl': row.length > 15 ? row[15].toString().trim() : '',
            });
          }
        }
        
        totalImported += fileQuestions.length;
        allImportedQuestions.addAll(fileQuestions);
      }
      
      if (allImportedQuestions.isEmpty) {
        setState(() {
          _isLoading = false;
          _statusMessage = '没有导入任何题目，请检查CSV文件格式';
        });
        return;
      }
      
      setState(() {
        _isLoading = false;
        _questions = allImportedQuestions;
        _statusMessage = '成功从${files.length}个文件中导入${totalImported}个题目';
      });
      
      // 询问用户是否要保存到数据库
      final shouldSave = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('保存到数据库', style: TextStyle(fontFamily: 'FangSong')),
          content: const Text('是否将导入的题目保存到数据库？', style: TextStyle(fontFamily: 'FangSong')),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消', style: TextStyle(fontFamily: 'FangSong')),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确定', style: TextStyle(fontFamily: 'FangSong')),
            ),
          ],
        ),
      ) ?? false;
      
      if (shouldSave) {
        await _saveQuestionsToDatabase(allImportedQuestions);
      } else {
        setState(() {
          _isLoading = false;
          _statusMessage = '已取消保存批量导入的题目';
        });
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _statusMessage = '批量导入题目失败: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('题目导入导出', style: TextStyle(fontFamily: 'FangSong')),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            // 返回并通知列表页面刷新
            Navigator.pop(context, true);
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.check),
            tooltip: '完成并返回',
            onPressed: () {
              // 返回并通知列表页面刷新
              Navigator.pop(context, true);
            },
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
            ElevatedButton(
              onPressed: _createSampleQuestions,
              child: const Text('创建示例题目', style: TextStyle(fontFamily: 'FangSong')),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _exportQuestions,
              child: const Text('导出题目', style: TextStyle(fontFamily: 'FangSong')),
            ),
            const Padding(
              padding: EdgeInsets.only(left: 16.0),
              child: Text('支持导出格式：CSV、Word（仅题目/题目+答案+解析）', 
                style: TextStyle(fontSize: 12, color: Colors.grey, fontFamily: 'FangSong')),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                ElevatedButton(
                  onPressed: _importQuestions,
                  child: const Text('导入题目', style: TextStyle(fontFamily: 'FangSong')),
                ),
                const SizedBox(width: 16),
                ElevatedButton(
                  onPressed: _importMultipleQuestions,
                  child: const Text('批量导入题目', style: TextStyle(fontFamily: 'FangSong')),
                ),
              ],
            ),
            const Padding(
              padding: EdgeInsets.only(left: 16.0),
              child: Text('支持导入格式：CSV、Excel（包含题目内容、选项、答案、解析、类型、分类、考点等字段）', 
                style: TextStyle(fontSize: 12, color: Colors.grey, fontFamily: 'FangSong')),
            ),
            const SizedBox(height: 24),
            Text('状态: $_statusMessage',
                style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong')),
            const SizedBox(height: 24),
            const Text('当前题目列表:',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, fontFamily: 'FangSong')),
            const SizedBox(height: 8),
            Expanded(
              child: _questions.isEmpty
                  ? const Center(child: Text('暂无题目数据', style: TextStyle(fontFamily: 'FangSong')))
                  : ListView.builder(
                      itemCount: _questions.length,
                      itemBuilder: (context, index) {
                        final question = _questions[index];
                        return Card(
                          margin: const EdgeInsets.only(bottom: 8),
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '${index + 1}. ${question['content']}',
                                  style: const TextStyle(fontWeight: FontWeight.bold, fontFamily: 'FangSong'),
                                ),
                                const SizedBox(height: 8),
                                Text('A. ${question['option_a']}', style: const TextStyle(fontFamily: 'FangSong')),
                                Text('B. ${question['option_b']}', style: const TextStyle(fontFamily: 'FangSong')),
                                Text('C. ${question['option_c']}', style: const TextStyle(fontFamily: 'FangSong')),
                                Text('D. ${question['option_d']}', style: const TextStyle(fontFamily: 'FangSong')),
                                const SizedBox(height: 8),
                                Text('正确答案: ${question['correct_answer']}',
                                    style: const TextStyle(color: Colors.green, fontFamily: 'FangSong')),
                                Text('解析: ${question['explanation']}', style: const TextStyle(fontFamily: 'FangSong')),
                                const SizedBox(height: 4),
                                Text(
                                  '类型: ${question['type']} | 分类: ${question['category']} | 考点: ${question['point']}',
                                  style: const TextStyle(fontSize: 12, color: Colors.grey, fontFamily: 'FangSong'),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}